/*
 * @Author: wuzhouhai wzh200x@126.com
 * @Date: 2024-05-29 16:00:08
 * @LastEditors: wuzhouhai wzh200x@126.com
 * @LastEditTime: 2024-08-05 18:13:31
 * @FilePath: \dwys_web\extensions\phoenix-plugin-client\assets\core\net\packet\packet.ts
 * @Description: 
 */
/*
 * @Author: wuzhouhai wzh200x@126.com
 * @Date: 2024-05-29 16:00:08
 * @LastEditors: wuzhouhai wzh200x@126.com
 * @LastEditTime: 2024-07-02 16:09:28
 * @FilePath: \phoenix-client-damo\assets\src\phoenix_client_sdk\net\packet\packet.ts
 * @Description: 
 */
import { IMessage } from "../../interface/iMessage";
import { UtilsArray } from "../../utils/Utils.Array";
import { MessageHeader } from "../message/header";

export class Packet {
    private _data : Uint8Array;
    private _message : IMessage;
    private isFinish: boolean;

    constructor(message : IMessage) {
        this._message = message;
        this.isFinish = false;
        this._data = new Uint8Array(0);
    }
    
    public setMessage(message : IMessage) {
        this._message = message;
    }   

    public getMessage<T>() : T {
        return this._message as T;
    }

    public getMessageEntity<T>() : T {
        return this._message.GetMessageEntity() as T;
    }

    public getOpcode() : number {
        return this._message.GetOpcode();
    }

    public getDataLength() : number {
        return this._data.length;
    }
    
    public finishPacket(verifyID:number){
        if (this.isFinish) {
            return this._data;
        }
        let msgData = this._message.Encode();
        let msgHeader = new MessageHeader();
        msgHeader.Length = msgData.length;
        msgHeader.VerifyID = verifyID;
        msgHeader.Opcode = this._message.GetOpcode();
        let headerData =  msgHeader.encode();
        // 合并_data和msgData
        this._data = UtilsArray.concatUint8Arrays(headerData, msgData);
        this.isFinish = true;
        return this._data;
    }

    public decode() {
        this._message.Decode(this._data);
    }

    public setData(data: Uint8Array){
        this._data = data;
        this.decode();
    }

    public getData() : Uint8Array {
        return this._data;
    }

}